package org.example.controller;


import org.example.exception.AppException;
import org.example.model.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public Object login(@RequestBody User user,
                        HttpServletRequest req){
        //根据账号，查询用户
        User condition = new User();
        condition.setUsername(user.getUsername());
        User exist = userService.selectByUsername(condition);
        if(exist == null) throw new AppException("USR001","账号不存在");
        if(!exist.getPassword().equals(user.getPassword())) {
            throw new AppException("USR002", "账号或者密码错误");
        }
        //登录成功
        HttpSession session = req.getSession();
        session.setAttribute("user",exist);
        return 1;//随便来个东西放在Body中
        //更灵活的一种方式
//        return ResponseEntity.ok().body(响应正文：也可以放二进制数据);
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();//让session失效
        return "redirect:/login.html";
    }
}
